package com.w.picture.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.w.picture.exception.ErrorCode;
import com.w.picture.exception.ThrowUtils;
import com.w.picture.mode.enums.FileUploadBizEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Title: FilePictureUpload
 * @Author wzp
 * @Date 2025/1/9 10:27
 * @description: 文件类型图片上传
 */
@Slf4j
@Component
public class FilePictureUpload extends PictureUploadTemplate {
    @Override
    public void validPicture(Object inputSource, FileUploadBizEnum bizEnum) {
        if (inputSource instanceof MultipartFile) {
            MultipartFile multipartFile = (MultipartFile) inputSource;
            ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");
            // 1. 校验文件大小
            long fileSize = multipartFile.getSize();
            ThrowUtils.throwIf(fileSize > bizEnum.getMaxSize(), ErrorCode.PARAMS_ERROR, "文件大小不能超过 " + bizEnum.getMaxSize() / (1024 * 1024) + "M");
            // 2. 校验文件后缀
            String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
            ThrowUtils.throwIf(!bizEnum.getAllowedFormats().contains(fileSuffix), ErrorCode.PARAMS_ERROR, "文件类型错误");
        }
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        if (inputSource instanceof MultipartFile) {
            MultipartFile multipartFile = (MultipartFile) inputSource;
            return multipartFile.getOriginalFilename();
        }
        return null;
    }

    @Override
    protected void processFile(Object inputSource, File file) throws IOException {
        if (inputSource instanceof MultipartFile) {
            MultipartFile multipartFile = (MultipartFile) inputSource;
            multipartFile.transferTo(file);
        }
    }
}
